﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Write.API.Command.MenuCommand;
using MediatR;

namespace B.S.BaseData.Write.API.CommandHandler.MenuHandler
{
    public class UpdateMenuHandler : IRequestHandler<UpdateMenuCommand, APIResult<object>>
    {
        private readonly IBaseRepository<MenuManagement> _baseRepository;
        private readonly IMapper _mapper;

        public UpdateMenuHandler(IBaseRepository<MenuManagement> baseRepository, IMapper mapper)
        {
            _baseRepository = baseRepository;
            _mapper = mapper;
        }

        public async Task<APIResult<object>> Handle(UpdateMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = APIEnum.Success;
            result.Msg = "修改成功";

            
            var entity = _mapper.Map<MenuManagement>(request);
            
            if (string.IsNullOrEmpty(entity.MenuName))
            {
                result.Code = APIEnum.Failed;
                result.Msg = "菜单名称不能为空值";
                return await Task.FromResult(result);
            }
            else if(string.IsNullOrEmpty(entity.MenuUrl))
            {
                result.Code = APIEnum.Failed;
                result.Msg = "菜单地址不能为空值";
                return await Task.FromResult(result);
            }
            var list = _baseRepository.GetAll().Where(p => p.MenuId == entity.MenuId&&p.MenuName==entity.MenuName).Count();
            if(list!=0)
            {
                result.Code = APIEnum.Failed;
                result.Msg = "同一菜单下菜单名重复了";
                return await Task.FromResult(result);
            }
            //entity.CreateTime = DateTime.Now;
            entity.CreateUser = "admin";
            entity.UpdateTime = DateTime.Now;
            entity.UpdateUser = "狗蛋";
            await _baseRepository.UpdateAsync(entity);
            return await Task.FromResult(result);
        }
    }
}
